package com.magicodex.bookkeeping.biz.accounting.event;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;

import com.magicodex.bookkeeping.R;
import com.magicodex.bookkeeping.biz.accounting.dto.AccountingDTO;
import com.magicodex.bookkeeping.biz.accounting.util.AccountingDataUtil;
import com.magicodex.bookkeeping.biz.common.constant.NumberConstants;
import com.magicodex.bookkeeping.ui.accounting.AccountingListViewAdapter;

import java.util.List;

/**
 * @author mh.z
 */
public class DeleteFabClickListener implements View.OnClickListener {
    private Activity activity;
    private AccountingListViewAdapter adapter;

    public DeleteFabClickListener(Activity activity, AccountingListViewAdapter adapter) {
        this.activity = activity;
        this.adapter = adapter;
    }

    @Override
    public void onClick(View view) {
        int position = adapter.getLastClickPosition();

        if (!(position >= 0 && position < adapter.getCount())) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(R.string.dialog_title_operation_tip);
        builder.setMessage(R.string.msg_confirm_delete);
        builder.setPositiveButton(R.string.button_confirm, createPositiveButtonClickListener());
        builder.setNegativeButton(R.string.button_cancel, createNegativeButtonClickListener());

        AlertDialog dialog = builder.create();
        // 显示对话框
        dialog.show();
    }

    /**
     * 点击确定按钮的事件监听器
     *
     * @return
     */
    protected DialogInterface.OnClickListener createPositiveButtonClickListener() {

        return (dialog, which) -> {
            int position = adapter.getLastClickPosition();

            List<AccountingDTO> recordList = adapter.getRecords();
            // 移除数据
            recordList.remove(position);

            if (!(position >= 0 && position < adapter.getCount())) {
                // 重置最后点击的位置
                adapter.setLastClickPosition(NumberConstants.NUMBER_NEG_1);

                View editFab = activity.findViewById(R.id.fab_edit);
                View deleteFab = activity.findViewById(R.id.fab_delete);
                // 设置编辑和删除按钮不可见
                editFab.setVisibility(View.INVISIBLE);
                deleteFab.setVisibility(View.INVISIBLE);
            }

            // 数据变更后处理
            AccountingDataUtil.notifyDataSetChanged(activity, adapter);
        };
    }

    /**
     * 点击取消按钮的事件监听器
     *
     * @return
     */
    protected DialogInterface.OnClickListener createNegativeButtonClickListener() {
        return (dialog, which) -> {
            //
        };
    }

}
